package com.ylyq.ylxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ylyq.ylxx.constants.AccountConstant;
import com.ylyq.ylxx.context.FilterContextHandler;
import com.ylyq.ylxx.entity.YlyqGroupInfo;
import com.ylyq.ylxx.entity.YlyqPlanStopStart;
import com.ylyq.ylxx.entity.YlyqRefusePlan;
import com.ylyq.ylxx.mapper.YlyqRefusePlanMapper;
import com.ylyq.ylxx.model.ResponseData;
import com.ylyq.ylxx.model.bean.*;
import com.ylyq.ylxx.model.request.*;
import com.ylyq.ylxx.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiaweichao
 * @since 2020-08-21
 */
@Service
@Slf4j
public class YlyqRefusePlanServiceImpl extends ServiceImpl<YlyqRefusePlanMapper, YlyqRefusePlan> implements IYlyqRefusePlanService {

    @Autowired
    private IOceaneginePlanService iOceaneginePlanService;
    @Autowired
    private IOceanegineCreativeService iOceanegineCreativeService;
    @Autowired
    private IYlyqPlanStopStartService iYlyqPlanStopStartService;
    @Autowired
    private IYlyqGroupInfoService iYlyqGroupInfoService;
    @Autowired
    private IOceanegineGroupService iOceanegineGroupService;

    @Override
    public ResponseData getRefusePlan(GetRefusePlanRequest getRefusePlanRequest) {

        QueryWrapper<YlyqRefusePlan> refusePlanQueryWrapper = new QueryWrapper<>();
        refusePlanQueryWrapper.eq("count", 3);
        refusePlanQueryWrapper.eq("advertiser_id", getRefusePlanRequest.getAdvertiser_id());
        List<YlyqRefusePlan> refusePlans = list(refusePlanQueryWrapper);
        if (null == refusePlans || refusePlans.isEmpty()) {
            return new ResponseData(ResponseData.Result.SUCCESS);
        }

        Map<Long, List<YlyqRefusePlan>> collectRefusePlans = refusePlans.stream().collect(Collectors.groupingBy(YlyqRefusePlan::getPlanIdCurrent));

        //排除掉被用户手动删除的计划，不然会导致iOceaneginePlanService.getRejectReason报错
        GetPlanInfoRequest getPlanInfoRequest = new GetPlanInfoRequest();
        getPlanInfoRequest.setAdvertiser_id(getRefusePlanRequest.getAdvertiser_id());
        getPlanInfoRequest.setPage_size(refusePlans.size());
        GetPlanInfoRequest.FilteringGetPlanInfoRequest filteringGetPlanInfoRequest = new GetPlanInfoRequest.FilteringGetPlanInfoRequest();
        filteringGetPlanInfoRequest.setIds(collectRefusePlans.keySet().toArray(new Long[collectRefusePlans.keySet().size()]));
        filteringGetPlanInfoRequest.setStatus("AD_STATUS_DELETE");//已删除
        getPlanInfoRequest.setFiltering(filteringGetPlanInfoRequest);
        OceanenginePlanInfo deletePlan = iOceaneginePlanService.getPlan(getPlanInfoRequest);
        if (null != deletePlan && null != deletePlan.getData() && null != deletePlan.getData().getList()) {
            List<OceanenginePlanInfo.DataBean.ListBean> list = deletePlan.getData().getList();
            if (!list.isEmpty()) {
                List<Long> collectDeletePlanId = list.stream().map(OceanenginePlanInfo.DataBean.ListBean::getId).collect(Collectors.toList());
                for (Long temp : collectDeletePlanId) {
                    if (collectRefusePlans.containsKey(temp)) {
                        collectRefusePlans.remove(temp);
                    }
                }

                QueryWrapper<YlyqRefusePlan> refusePlanQueryWrapper1 = new QueryWrapper<>();
                refusePlanQueryWrapper1.in("plan_id_current", collectDeletePlanId);
                remove(refusePlanQueryWrapper1);
            }
        }

//以组为键，组下的被拒绝计划集合为值
        Map<Long, List<OceanengineRejectReasonResult.DataBean.ListBean>> refuseResults = new HashMap<>();
        List<OceanengineRejectReasonResult.DataBean.ListBean> rejectReasonList = new ArrayList<>();

        List<Long> result = new ArrayList<>(collectRefusePlans.keySet());

        int m = 0;
        while (result.size() > 10 * m) {//因为最多传10个广告计划id
            List<Long> planIdsTemp;
            if (result.size() > 10 * (m + 1)) {
                planIdsTemp = result.subList(m * 10, 10 * (m + 1));
            } else {
                planIdsTemp = result.subList(m * 10, result.size());
            }

            OceanengineRejectReasonResult rejectReason = iOceaneginePlanService.getRejectReason(new GetRejectReasonRequest(getRefusePlanRequest.getAdvertiser_id(), planIdsTemp.toArray(new Long[planIdsTemp.size()])));
            if (rejectReason.getCode() == AccountConstant.SUCCESS && rejectReason.getData().getList() != null)
                rejectReasonList.addAll(rejectReason.getData().getList());

            m++;
        }

        for (OceanengineRejectReasonResult.DataBean.ListBean temp : rejectReasonList) {
            Long groupId = collectRefusePlans.get(temp.getAd_reject().getAd_id()).get(0).getGroupId();
            if (refuseResults.containsKey(groupId)) {
                refuseResults.get(groupId).add(temp);
            } else {
                refuseResults.put(groupId, new ArrayList<>(Arrays.asList(temp)));
            }
        }

        GetGroupRequest getGroupRequest = new GetGroupRequest();
        getGroupRequest.setAdvertiser_id(getRefusePlanRequest.getAdvertiser_id());
        getGroupRequest.setPage_size(refuseResults.size());
        getGroupRequest.setFields(new String[]{"id", "name"});
        GetGroupRequest.FilteringGetGroupInfoRequest filteringGetGroupInfoRequest = new GetGroupRequest.FilteringGetGroupInfoRequest();
        filteringGetGroupInfoRequest.setIds(refuseResults.keySet().toArray(new Long[refuseResults.keySet().size()]));
        getGroupRequest.setFiltering(filteringGetGroupInfoRequest);
        OceanengineGroupInfo group = iOceanegineGroupService.getGroup(getGroupRequest);
        Map<Long, List<OceanengineGroupInfo.OceanengineGroupDataBean.OceanengineGroupListBean>> collectGroup=null;
        if (group != null && null != group.getData().getList() && !group.getData().getList().isEmpty())
            collectGroup = group.getData().getList().stream().collect(Collectors.groupingBy(OceanengineGroupInfo.OceanengineGroupDataBean.OceanengineGroupListBean::getId));


        Map<Long, List<YlyqGroupInfo>> groupInfoList = null;
        if(null!=refuseResults.keySet()&&!refuseResults.keySet().isEmpty()){
            QueryWrapper<YlyqGroupInfo> groupInfoQueryWrapper = new QueryWrapper<>();
            groupInfoQueryWrapper.in("group_id", refuseResults.keySet().toArray(new Long[refuseResults.keySet().size()]));
            groupInfoQueryWrapper.select("group_id", "choose_url", "choose_code_url");
            List<YlyqGroupInfo> ylyqGroupInfoList = iYlyqGroupInfoService.list(groupInfoQueryWrapper);
            if (ylyqGroupInfoList != null && !ylyqGroupInfoList.isEmpty())
                groupInfoList = ylyqGroupInfoList.stream().collect(Collectors.groupingBy(YlyqGroupInfo::getGroupId));
        }


        List<RefusePlanResponse> resultRefusePlans = new ArrayList<>();
        for (Map.Entry<Long, List<OceanengineRejectReasonResult.DataBean.ListBean>> entry : refuseResults.entrySet()) {
            Long groupId = entry.getKey();
            List<OceanengineRejectReasonResult.DataBean.ListBean> groupIdReasonList = entry.getValue();
            RefusePlanResponse refusePlanResponse = new RefusePlanResponse();
            refusePlanResponse.setAdvertiserId(getRefusePlanRequest.getAdvertiser_id());
            if (groupInfoList != null && groupInfoList.get(groupId) != null) {
                refusePlanResponse.setChooseCodeUrl(groupInfoList.get(groupId).get(0).getChooseCodeUrl());
                refusePlanResponse.setChooseUrl(groupInfoList.get(groupId).get(0).getChooseUrl());
            }
            if (collectGroup != null && collectGroup.get(groupId) != null) {
                refusePlanResponse.setGroupName(collectGroup.get(groupId).get(0).getName());
            }
            refusePlanResponse.setGroupId(groupId);
            refusePlanResponse.setPlans(groupIdReasonList);
            resultRefusePlans.add(refusePlanResponse);
        }
        return new ResponseData(ResponseData.Result.SUCCESS, resultRefusePlans);
    }

    @Override
    public ResponseData changeRefusePlan(ChangeRefusePlanRequest changeRefusePlanRequest) {
        GetPlanInfoRequest getPlanInfoRequest = new GetPlanInfoRequest();
        getPlanInfoRequest.setAdvertiser_id(changeRefusePlanRequest.getAdvertiser_id());
//        getPlanInfoRequest.setPage_size(planId.length);
        GetPlanInfoRequest.FilteringGetPlanInfoRequest filteringGetPlanInfoRequest = new GetPlanInfoRequest.FilteringGetPlanInfoRequest();
        filteringGetPlanInfoRequest.setIds(new Long[]{changeRefusePlanRequest.getPlan_id()});
        getPlanInfoRequest.setFiltering(filteringGetPlanInfoRequest);
        OceanenginePlanInfo planInfo = iOceaneginePlanService.getPlan(getPlanInfoRequest);
        if (null == planInfo) {
            return new ResponseData(ResponseData.Result.FAIL);
        }
        if (planInfo.getCode() == AccountConstant.SUCCESS) {
            List<OceanenginePlanInfo.DataBean.ListBean> planInfoList = planInfo.getData().getList();
            if (null == planInfoList || planInfoList.isEmpty())
                return new ResponseData(ResponseData.Result.FAIL);

            // 巨量新建
            CreatePlanInfoRequest createPlanInfoRequest = new CreatePlanInfoRequest();
            BeanUtils.copyProperties(planInfoList.get(0), createPlanInfoRequest);
            createPlanInfoRequest.setName(createPlanInfoRequest.getName() + "_change");

            //提交修改的内容，
            if (StringUtils.isNotBlank(changeRefusePlanRequest.getExternal_url()))
                createPlanInfoRequest.setExternal_url(changeRefusePlanRequest.getExternal_url());


            OceanengineCreatePlanResult planResult = iOceaneginePlanService.createPlan(createPlanInfoRequest);
            if (planResult.getCode() == AccountConstant.SUCCESS) {
                //取前计划的创意详情
                CreativeDetailRequest creativeDetailRequest = new CreativeDetailRequest();
                creativeDetailRequest.setAd_id(changeRefusePlanRequest.getPlan_id());
                creativeDetailRequest.setAdvertiser_id(changeRefusePlanRequest.getAdvertiser_id());
                OceanengineCreativeDetail oceanengineCreativeDetail = iOceanegineCreativeService.creativeDetail(creativeDetailRequest);

                if (oceanengineCreativeDetail.getCode() == AccountConstant.SUCCESS) {//新建计划。不管成功与否，关联计划得创意都要删除
                    //新建创意
                    CreateCreativeRequest createCreativeRequest = new CreateCreativeRequest();
                    BeanUtils.copyProperties(oceanengineCreativeDetail.getData(), createCreativeRequest);
                    createCreativeRequest.setAd_id(planResult.getData().getAd_id());

                    //提交修改的内容，
                    if (null != changeRefusePlanRequest.getCreatives() && !changeRefusePlanRequest.getCreatives().isEmpty()) {
                        createCreativeRequest.setCreatives(changeRefusePlanRequest.getCreatives());
                    }
                    if (null != changeRefusePlanRequest.getImage_list() && !changeRefusePlanRequest.getImage_list().isEmpty()) {
                        createCreativeRequest.setImage_list(changeRefusePlanRequest.getImage_list());
                    }
                    if (null != changeRefusePlanRequest.getTitle_list() && !changeRefusePlanRequest.getTitle_list().isEmpty()) {
                        createCreativeRequest.setTitle_list(changeRefusePlanRequest.getTitle_list());
                    }
                    if (StringUtils.isNotBlank(changeRefusePlanRequest.getSource())) {
                        createCreativeRequest.setSource(changeRefusePlanRequest.getSource());
                    }


                    OceanengineCreateCreativeResult creative = iOceanegineCreativeService.createCreative(createCreativeRequest);
//                                    creative.getCode();
                }
                //易量新建
                YlyqPlanStopStart ylyqPlanStopStart = new YlyqPlanStopStart();
                ylyqPlanStopStart.setPlanId(planResult.getData().getAd_id());
                ylyqPlanStopStart.setAdvertiserId(changeRefusePlanRequest.getAdvertiser_id());
                ylyqPlanStopStart.setGroupId(createPlanInfoRequest.getCampaign_id());
                ylyqPlanStopStart.setUserId(FilterContextHandler.getUserID());
                iYlyqPlanStopStartService.save(ylyqPlanStopStart);

                if (!planInfoList.isEmpty()) {
                    //巨量删除原计划
                    Long[] resultPlanIds = planInfoList.stream().map(OceanenginePlanInfo.DataBean.ListBean::getId).collect(Collectors.toList()).toArray(new Long[planInfoList.size()]);

                    UpdatePlanStateInfoRequest updatePlanStateInfoRequest = new UpdatePlanStateInfoRequest();
                    updatePlanStateInfoRequest.setAdvertiser_id(changeRefusePlanRequest.getAdvertiser_id());
                    updatePlanStateInfoRequest.setOpt_status("delete");
                    updatePlanStateInfoRequest.setAd_ids(resultPlanIds);
                    OceanengineUpdatePlanStateResult oceanengineUpdatePlanStateResult = iOceaneginePlanService.updateBatchPlanState(updatePlanStateInfoRequest);

                    //易量删除原计划
                    QueryWrapper<YlyqPlanStopStart> removeMap = new QueryWrapper<>();
                    removeMap.in("plan_id", resultPlanIds);
                    removeMap.eq("advertiser_id", changeRefusePlanRequest.getAdvertiser_id());
                    iYlyqPlanStopStartService.remove(removeMap);
                    log.info("被拒绝的计划=====advertiserid==" + changeRefusePlanRequest.getAdvertiser_id() + "planid====" + resultPlanIds.toString() + "，成功从易量删除");
                }

                return new ResponseData(ResponseData.Result.SUCCESS);
            }
        }
        return new ResponseData(ResponseData.Result.FAIL);
    }
}